<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能PPT生成器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .input-section {
            margin-bottom: 20px;
        }
        textarea {
            width: 100%;
            height: 300px;
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
        }
        .button-group {
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        button.secondary {
            background-color: #2196F3;
        }
        button:hover:not(:disabled) {
            opacity: 0.9;
        }
        .loading {
            display: none;
            text-align: center;
            margin-top: 10px;
        }
        .error {
            color: red;
            text-align: center;
            margin-top: 10px;
            display: none;
        }
        .tips {
            background-color: #e8f5e9;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
        }
        .preview-section {
            display: none;
            margin-top: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }
        .slide-preview {
            margin: 15px 0;
            padding: 15px;
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .slide-preview h3 {
            color: #2196F3;
            margin-top: 0;
        }
        .slide-preview .content {
            margin: 10px 0;
        }
        .slide-preview .image-suggestion {
            color: #666;
            font-style: italic;
        }
        .generate-image-btn {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .image-result {
            margin-top: 10px;
            max-width: 100%;
        }
        .image-result img {
            max-width: 300px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            width: 300px;
            border-radius: 5px;
        }
        .modal-content select {
            width: 100%;
            padding: 8px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .modal-content button {
            margin: 5px;
            padding: 8px 16px;
        }
        
        .image-result {
            margin-top: 10px;
            text-align: center;
        }
        
        .image-result img {
            max-width: 300px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>智能PPT生成器</h1>
        <div class="input-section">
            <textarea id="inputText" placeholder="在此输入或粘贴文本内容..."></textarea>
        </div>
        <div class="button-group">
            <button onclick="analyzePPT()">分析内容</button>
            <input type="file" id="templateFile" accept=".pptx" style="display: none" onchange="uploadTemplate()">
            <button class="secondary" onclick="document.getElementById('templateFile').click()">上传PPT模板</button>
            <button id="exportBtn" onclick="generatePPT()" disabled>导出PPT</button>
            <button class="secondary" onclick="clearText()">清空内容</button>
        </div>
        <div id="templateStatus" style="display: none; margin: 10px 0; padding: 10px; background-color: #e3f2fd; border-radius: 4px;">
            <span>已上传模板：<span id="templateName"></span></span>
            <button onclick="removeTemplate()" style="padding: 2px 8px; margin-left: 10px; background-color: #f44336;">删除模板</button>
        </div>
        <div class="tips">
            <h3>使用说明：</h3>
            <ol>
                <li>在下方输入框中粘贴或输入您想要转换为PPT的文本内容</li>
                <li>可选：上传PPT模板文件（.pptx格式）</li>
                <li>点击"分析内容"，系统将自动：
                    <ul>
                        <li>分析文本结构（总-分-结构）</li>
                        <li>提取关键词和重点内容</li>
                        <li>生成适当的标题</li>
                        <li>提供配图建议</li>
                    </ul>
                </li>
                <li>检查预览内容，确认无误后点击"导出PPT"</li>
            </ol>
        </div>
        <div id="previewSection" class="preview-section">
            <h2>内容预览</h2>
            <div id="slidePreview"></div>
        </div>
        <div id="loading" class="loading">加载中...</div>
        <div id="error" class="error"></div>
    </div>

    <!-- 模型选择对话框 -->
    <div id="modelDialog" class="modal">
        <div class="modal-content">
            <h3>选择图像生成模型</h3>
            <select id="modelSelect">
                <!-- 模型选项将通过 JavaScript 动态加载 -->
            </select>
            <button onclick="confirmModelSelection()">确认</button>
            <button onclick="closeModelDialog()">取消</button>
        </div>
    </div>

    <script>
        let pptContent = null;
        let templateFile = null;
        let currentImageIndex = null;
        let currentPrompt = null;

        async function analyzePPT() {
            const inputText = document.getElementById('inputText').value.trim();
            if (!inputText) {
                alert('请输入文本内容');
                return;
            }

            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            loading.style.display = 'block';
            error.style.display = 'none';

            try {
                const response = await fetch('/analyze_ppt/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ text: inputText })
                });

                if (response.ok) {
                    pptContent = await response.json();
                    displayPreview(pptContent);
                    document.getElementById('exportBtn').disabled = false;
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '分析失败');
                }
            } catch (err) {
                error.textContent = '错误：' + err.message;
                error.style.display = 'block';
            } finally {
                loading.style.display = 'none';
            }
        }

        function displayPreview(content) {
            const previewSection = document.getElementById('previewSection');
            const slidePreview = document.getElementById('slidePreview');
            slidePreview.innerHTML = '';

            content.slides.forEach((slide, index) => {
                const slideDiv = document.createElement('div');
                slideDiv.className = 'slide-preview';
                slideDiv.innerHTML = `
                    <h3>第 ${index + 1} 页：${slide.title}</h3>
                    <div class="content">${slide.content}</div>
                    <div class="image-suggestion">
                        建议配图：${slide.image_suggestion}
                        <button onclick="generateImage(${index}, '${slide.image_suggestion}')" class="generate-image-btn">生成图片</button>
                        <div id="image-result-${index}" class="image-result"></div>
                    </div>
                    <div class="keywords">关键词：${slide.keywords.join('、')}</div>
                `;
                slidePreview.appendChild(slideDiv);
            });

            previewSection.style.display = 'block';
        }

        async function uploadTemplate() {
            const input = document.getElementById('templateFile');
            if (input.files && input.files[0]) {
                const file = input.files[0];
                const formData = new FormData();
                formData.append('file', file);

                try {
                    const response = await fetch('/upload_template/', {
                        method: 'POST',
                        body: formData
                    });

                    if (response.ok) {
                        const result = await response.json();
                        templateFile = file;
                        document.getElementById('templateName').textContent = file.name;
                        document.getElementById('templateStatus').style.display = 'block';
                    } else {
                        throw new Error('模板上传失败');
                    }
                } catch (err) {
                    alert('模板上传失败：' + err.message);
                }
            }
        }

        function removeTemplate() {
            templateFile = null;
            document.getElementById('templateFile').value = '';
            document.getElementById('templateStatus').style.display = 'none';
        }

        async function generatePPT() {
            if (!pptContent) {
                alert('请先分析内容');
                return;
            }

            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            loading.style.display = 'block';
            error.style.display = 'none';

            try {
                let response;
                if (templateFile) {
                    // 使用模板生成PPT
                    const formData = new FormData();
                    formData.append('ppt_content', JSON.stringify(pptContent));
                    formData.append('template_file', templateFile);
                    
                    response = await fetch('/generate_ppt_with_template/', {
                        method: 'POST',
                        body: formData
                    });
                } else {
                    // 不使用模板生成PPT
                    response = await fetch('/generate_ppt/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ slides: pptContent.slides })  // 确保数据格式正确
                    });
                }

                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'generated_slides.pptx';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '生成PPT失败');
                }
            } catch (err) {
                error.textContent = '错误：' + err.message;
                error.style.display = 'block';
            } finally {
                loading.style.display = 'none';
            }
        }

        function clearText() {
            document.getElementById('inputText').value = '';
            document.getElementById('previewSection').style.display = 'none';
            document.getElementById('exportBtn').disabled = true;
            pptContent = null;
            removeTemplate();
        }

        function generateImage(index, prompt) {
            currentImageIndex = index;
            currentPrompt = prompt;
            document.getElementById('modelDialog').style.display = 'block';
        }

        function closeModelDialog() {
            document.getElementById('modelDialog').style.display = 'none';
        }

        async function confirmModelSelection() {
            const model = document.getElementById('modelSelect').value;
            closeModelDialog();
            
            const imageResult = document.getElementById(`image-result-${currentImageIndex}`);
            imageResult.innerHTML = '生成图片中...';
            
            try {
                const response = await fetch('/generate_image/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        prompt: currentPrompt,
                        model: model
                    })
                });
                
                if (response.ok) {
                    const data = await response.json();
                    imageResult.innerHTML = `<img src="${data.image_url}" alt="生成的图片">`;
                } else {
                    const error = await response.json();
                    imageResult.innerHTML = `生成失败：${error.detail || error.error}`;
                }
            } catch (err) {
                imageResult.innerHTML = `生成失败：${err.message}`;
            }
        }

        // 加载可用的图像生成模型
        async function loadImageModels() {
            try {
                const response = await fetch('/available_image_models');
                if (response.ok) {
                    const data = await response.json();
                    const modelSelect = document.getElementById('modelSelect');
                    modelSelect.innerHTML = data.models.map(model => 
                        `<option value="${model.id}" title="${model.description}">${model.name}</option>`
                    ).join('');
                }
            } catch (err) {
                console.error('加载模型列表失败:', err);
            }
        }

        // 在页面加载时获取可用模型
        document.addEventListener('DOMContentLoaded', loadImageModels);
    </script>
</body>
</html>